import Request from '@/js_sdk/luch-request/luch-request/index.js'
import {
	useUserStore
} from '@/stores/index.js'


const pagesList = [
	"pages/index/index",
	"pages/wiki/wiki",
	"pages/notify/notify",
	"pages/my/my",
]

const whitelist = ["/code", "/login/password", "/login"]

export const http = new Request({
	baseURL: 'https://consult-api.itheima.net',
	// https://t1ps66c7na.hk.aircode.run
	// https://consult-api.itheima.net
	// timeout:3000,
})


// 请求拦截前
http.interceptors.request.use((config) => {
	// console.log(config);
	const store = useUserStore()
	const defaultHeader = {}
	if (store.token && !whitelist.includes(config.url)) {
		defaultHeader.Authorization = 'Bearer ' + store.token
	}
	// 这里扩展是因为局部传进来的数据要合并覆盖全局的数据
	config.header = {
		...defaultHeader,
		...config.header
	}


	return config
})

// 响应拦截
http.interceptors.response.use((response) => { //响应成功等于200做什么
	// console.log(response);
	return Promise.resolve(response.data)
}, (error) => {
	//响应错误做什么（statuscode!=200
	// 后端约定 token 过期（失效）时，状态码值为 401
	if (error.statusCode === 401) relogin()


	return Promise.reject(error)

})




// 如果401就跳转登录页面
function relogin() {
	// 获取页面栈获取方法
	const Pages = getCurrentPages()
	// 获取到当前页面
	const CurrentPage = Pages[Pages.length - 1]
	console.log(Pages);
	console.log(CurrentPage.$page.fullPath);
	
	// 获取到当前页面的路由 这里为什么不用route 而用fullPath 因为fullPath路径更全
	const reurl = CurrentPage.$page.fullPath =="/pages/login/login" ? "pages/index/index": CurrentPage.$page.fullPath
	const opentype = pagesList.includes(CurrentPage.route) ? 'switchTab' : 'redirectTo'
	const UserStore = useUserStore()
	// 跳转地址
	UserStore.reurl = reurl
	// 跳转方式
	UserStore.jumpmethod = opentype
	uni.redirectTo({
		url: `/pages/login/login`,
	})
}